package com.aidong.util;

/**
 * Created by john on 16-11-2.
 */
import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

public class ExportXlsx {
    protected HttpServletResponse response;
    protected OutputStream outputStream;
    protected Workbook workBook;
    protected Sheet sheet;
    protected int rowNum;

    public ExportXlsx(String fileName, String sheetName) throws Exception {
        this.outputStream = new FileOutputStream(fileName);
        this.workBook = new SXSSFWorkbook(100);
        this.sheet = this.workBook.createSheet(sheetName);
        this.rowNum = 0;
    }

    public ExportXlsx(HttpServletResponse response, String fileName, String sheetName) throws Exception {
        this.response = response;
        String fn = new String(fileName.getBytes(), "iso-8859-1");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment; filename=" + fn + ".xlsx");
        this.outputStream = response.getOutputStream();
        this.workBook = new SXSSFWorkbook(100);
        this.sheet = this.workBook.createSheet(sheetName);
        this.rowNum = 0;
    }

    public Sheet getSheet() {
        return this.sheet;
    }

    public Sheet addSheet(String sheetName) {
        this.sheet = this.workBook.createSheet(sheetName);
        this.rowNum = 0;
        return this.sheet;
    }

    public void setWidth(int... wid) {
        for(int i = 0; i < wid.length; ++i) {
            this.sheet.setColumnWidth(i, wid[i] * 256);
        }

    }

    public int addHead(String... name) throws Exception {
        Row row = this.sheet.createRow(this.rowNum);

        for(int i = 0; i < name.length; ++i) {
            row.createCell(i).setCellValue(name[i]);
        }

        ++this.rowNum;
        return this.rowNum;
    }

    public int addRow(Object... value) throws Exception {
        Row row = this.sheet.createRow(this.rowNum);

        for(int i = 0; i < value.length; ++i) {
            if(value[i] != null) {
                if(value[i] instanceof Number) {
                    row.createCell(i).setCellValue(((Number)value[i]).doubleValue());
                } else {
                    row.createCell(i).setCellValue(value[i].toString());
                }
            }
        }

        ++this.rowNum;
        return this.rowNum;
    }

    public void close() throws Exception {
        this.workBook.write(this.outputStream);
        this.outputStream.flush();
        this.outputStream.close();
    }
}
